using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Common;
using System.Globalization;
using System.Collections;
using System.Text;
using System.Data;
using System.Web.Configuration;

public partial class Templates : System.Web.UI.Page
{
    private Database db;
    /// <summary>
    /// Disables gridlines if there are no templates
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        pnlAddError.Visible = false;
        if(!Page.IsPostBack) {
            mltMain.ActiveViewIndex = 0;
        }
    }

    protected void dsMain_Init(object sender, EventArgs e) {
        dsMain.SelectCommand = "SELECT id, name FROM " + WebConfigurationManager.AppSettings["TablePrefix"] + "templates";
    }

    /// <summary>
    /// Process edit/delete commands from the GridView
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCommandEventArgs"/> instance containing the event data.</param>
    protected void grdTemplates_RowCommand(object sender, GridViewCommandEventArgs e) {
        db = new Database();
        switch(e.CommandName) {
            case "doedit":
                mltMain.ActiveViewIndex = 1;
                using(Database.Command cmd = db.CreateCommand()) {
                    db.OpenConnection();
                    cmd.CommandText = "SELECT * FROM " + db.TablePrefix + "templates WHERE id = @p";
                    cmd.AddParameterWithValue("@p", e.CommandArgument.ToString());
                    DbDataReader reader = cmd.ExecuteReader();
                    string templateId = string.Empty;
                    while(reader.Read()) {
                        txtTemplateName.Text = reader["name"].ToString();
                        txtFileName.Text = reader["filename"].ToString();
                        txtFileStart.Text = reader["filestart"].ToString();
                        txtFileEnd.Text = reader["fileend"].ToString();
                        txtFileElement.Text = reader["line"].ToString();
                        ViewState["templateid"] = reader["id"];
                        ViewState["editing"] = bool.TrueString;
                        Page.Title = "Editing Template - " + txtTemplateName.Text + " &raquo; ResourceBlender";
                        lblEditTemplates.Text = "Edit Template - " + txtTemplateName.Text;
                        litNavAddAddTemplate.Text = "Edit Template";
                    }
                    reader.Close();
                }
                break;
            case "confirmdelete":
                mltMain.ActiveViewIndex = 2;
                ViewState["templateid"] = e.CommandArgument.ToString();
                using(Database.Command cmd = db.CreateCommand()) {
                    db.OpenConnection();
                    cmd.CommandText = "SELECT name FROM " + db.TablePrefix + "templates WHERE id = @p";
                    cmd.AddParameterWithValue("@p", e.CommandArgument.ToString());
                    string templateName = cmd.ExecuteScalar().ToString();
                    lblConfirmDelete.Text = string.Format("Are you sure you want to delete the template <em>{0}</em>?", templateName);
                    Page.Title = "Delete Template &raquo; ResourceBlender";
                }
                break;
            default:
                mltMain.ActiveViewIndex = 0;
                break;
        }
        db.CloseConnection();
    }

    /// <summary>
    /// Binds the grid and removes gridlines if necessary.
    /// </summary>
    private void BindGrid() {
        grdTemplates.DataBind();
        if(grdTemplates.Rows.Count == 0) {
            grdTemplates.GridLines = GridLines.None;
        } else {
            grdTemplates.GridLines = GridLines.Both;
        }
    }

    #region Adding/Editing

    /// <summary>
    /// Shows a form to add a new template.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void lnkNewTemplate_Click(object sender, EventArgs e) {
        mltMain.ActiveViewIndex = 1;
        Page.Title = "New Template &raquo; ResourceBlender";
        ViewState["templateid"] = Utils.GenID(true);
        ViewState["editing"] = bool.FalseString;
    }

    /// <summary>
    /// Saves or adds the template.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e) {
        if(Page.IsValid) {
            bool editing = false;
            string templateId = null;
            try {
                editing = bool.Parse(ViewState["editing"].ToString());
                templateId = ViewState["templateid"].ToString();
            } catch {
                mltMain.ActiveViewIndex = 3;
                lblErrorDescription.Text = "Error loading viewstate data, try refreshing the page.";
                return;
            }
            if(db == null) {
                db = new Database();
            }
            db.OpenConnection();
            using(Database.Command cmd = db.CreateCommand()) {
                cmd.CommandText = "SELECT COUNT(id) FROM " + db.TablePrefix + "templates WHERE name = @name AND id != @id";
                cmd.AddParameterWithValue("@name", txtTemplateName.Text);
                cmd.AddParameterWithValue("@id", templateId);
                int numExistingTemplates = int.Parse(cmd.ExecuteScalar().ToString());
                if(numExistingTemplates > 0) {
                    lblAddError.Text = "Template already exists";
                    pnlAddError.Visible = true;
                } else {
                    if(editing) {
                        cmd.CommandText = "UPDATE " + db.TablePrefix + "templates SET name = @name, filename = @filename, filestart = @filestart, line = @line, fileend = @fileend WHERE id = @id";
                    } else {
                        cmd.CommandText = "INSERT INTO " + db.TablePrefix + "templates (name, filename, filestart, line, fileend) VALUES (@name, @filename, @filestart, @line, @fileend)";
                    }
                    cmd.AddParameterWithValue("@filename", txtFileName.Text);
                    cmd.AddParameterWithValue("@filestart", txtFileStart.Text);
                    cmd.AddParameterWithValue("@line", txtFileElement.Text);
                    cmd.AddParameterWithValue("@fileend", txtFileEnd.Text);
                    cmd.ExecuteNonQuery();
                    txtTemplateName.Text = string.Empty;
                    txtFileName.Text = string.Empty;
                    txtFileStart.Text = string.Empty;
                    txtFileEnd.Text = string.Empty;
                    txtFileElement.Text = string.Empty;
                    mltMain.ActiveViewIndex = 0;
                    BindGrid();
                }
            }
            db.CloseConnection();
        }
    }
    #endregion

    #region Deleting
    /// <summary>
    /// Confirms deletion of a template and removes it from the database.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnOk_Click(object sender, EventArgs e) {
        db = new Database();
        db.OpenConnection();
        using(Database.Command cmd = db.CreateCommand()) {
            cmd.CommandText = "DELETE FROM " + db.TablePrefix + "templates WHERE id = @p";
            cmd.AddParameterWithValue("@p", ViewState["templateid"].ToString());
            cmd.ExecuteNonQuery();
        }
        db.CloseConnection();
        mltMain.ActiveViewIndex = 0;
        BindGrid();
    }
    
    /// <summary>
    /// Redirects the user to the 'Manage templates' page.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnCancelDelete_Click(object sender, EventArgs e) {
        mltMain.ActiveViewIndex = 0;
    }
    #endregion

}
